/*
 * 表格穿梭框
 */
import React, { useState, useEffect } from 'react';
import { Transfer, Radio, Table, Form } from 'antd';
import './index.less';

function difference(arr, ...args) {
    let temp = [];
    let result = [];
    for (let item of args) {
        if (Array.isArray(item)) {
            for (let subItem of item) {
                temp.push(subItem);
            }
        } else {
            temp.push(item);
        }
    }
    for (let item of arr) {
        if (!temp.includes(item)) {
            result.push(item);
        }
    }
    return result;
}

const HcpTableTransfer = (props) => {
    const {
        leftColumns, // 左侧表格列
        rightColumns, // 右侧表格列
        leftLengthMax, // 左侧开始滚动条数
        rightLengthMax, // 右侧开始滚动条数
        pagination, // 表格分页
        dataSource, // 初始所有数据源
        targetKeys, // 初始选中数据源
        onChange,
        disabledHandle, // 禁止操作列
        form,
        ...restProps
    } = props;

    const [tableTargetKeys, setTableTargetKeys] = useState(targetKeys);

    useEffect(() => {
        setTableTargetKeys(targetKeys);
    }, [targetKeys]);

    const handleSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
        // console.log('sourceSelectedKeys',sourceSelectedKeys);
        // console.log('targetSelectedKeys',targetSelectedKeys);
        let source = [...sourceSelectedKeys];
        let target = [...targetSelectedKeys];
        sourceSelectedKeys.length = 0;
        targetSelectedKeys.length = 0;
        let keys = [];
        if (source.length > 0) {
            keys = [...source, ...tableTargetKeys];
            // console.log('1', keys);
            setTableTargetKeys(keys);
        }
        if (target.length > 0) {
            keys = difference(tableTargetKeys, target);
            // console.log('2', keys);
            setTableTargetKeys(keys);
        }
        if(typeof onChange == "function") onChange(keys);
    };

    const rightColumnsFun = (
        rightColumns,
        onItemSelect,
        onItemSelectAll,
        tableTargetKeys
    ) => {
        let columns = [...rightColumns];
        columns.push({
            title: (
                <span
                    className="iconfont icon-delete"
                    onClick={(e) => {
                        onItemSelectAll([...tableTargetKeys], true);
                    }}
                 />
            ),
            render: (text, record, index) => {
                let disabled = disabledHandle?.key
                    ? record[disabledHandle.key] === disabledHandle.value
                    : false;
                return (
                    <span
                        className="iconfont icon-delete"
                        disabled={disabled}
                        onClick={(e) => {
                            if (!disabled) {
                                onItemSelect(record.key, true);
                            }
                        }}
                     />
                );
            },
        });
        return columns;
    };

    return (
        <Transfer
            {...restProps}
            showSelectAll={false}
            pagination={false}
            className="hcp_table_transfer"
            onSelectChange={handleSelectChange}
            dataSource={dataSource}
            targetKeys={tableTargetKeys}
            oneWay
        >
            {({
                direction,
                filteredItems,
                onItemSelectAll,
                onItemSelect,
                selectedKeys: listSelectedKeys,
                disabled: listDisabled,
            }) => {
                const columns =
                    direction === 'left'
                        ? leftColumns
                        : rightColumnsFun(
                              rightColumns,
                              onItemSelect,
                              onItemSelectAll,
                              tableTargetKeys
                          );
                columns.forEach((item) => {
                    item.align = 'center';
                    if (item.showTotal) {
                        // 给列表第一个字段加total数量，单独设置showTotal=true,displayName=名称
                        item.title = `${item.displayName} (${filteredItems.length})`;
                    }
                    return item;
                });
                const rowSelection = {
                    getCheckboxProps: (item) => ({ disabled: listDisabled }),
                    onSelectAll(selected, selectedRows) {
                        const treeSelectedKeys = selectedRows
                            .filter(Boolean)
                            .map(({ key }) => key);
                        const diffKeys = selected
                            ? difference(treeSelectedKeys, listSelectedKeys)
                            : difference(listSelectedKeys, treeSelectedKeys);
                        onItemSelectAll(diffKeys, selected);
                    },
                    onSelect({ key }, selected) {
                        onItemSelect(key, selected);
                    },
                    selectedRowKeys: listSelectedKeys,
                };

                return (
                    <Table
                        style={{ height: '100%', textAlign: 'center' }}
                        rowSelection={direction === 'left' && rowSelection}
                        columns={columns}
                        dataSource={filteredItems}
                        size="small"
                        pagination={pagination}
                        scroll={
                            filteredItems.length >
                            ((direction === 'left'
                                ? leftLengthMax
                                : rightLengthMax) || 5)
                                ? { x: '100%', y: 170 }
                                : {}
                        }
                    />
                );
            }}
        </Transfer>
    );
};

export default HcpTableTransfer;
